package cn.mengfly.testnrz.netty.protobuf;

import cn.mengfly.testnrz.json.JsonUtil;
import cn.mengfly.testnrz.nio.NioDemoConfig;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.string.StringEncoder;

import java.nio.charset.StandardCharsets;

public class JsonSendClient {

    Bootstrap bootstrap = new Bootstrap();

    public void runClient() {
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            bootstrap.group(workerGroup);
            bootstrap.channel(NioSocketChannel.class);
            bootstrap.remoteAddress(NioDemoConfig.SOCKET_IP, NioDemoConfig.SOCKET_PORT);
            bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
            bootstrap.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
            bootstrap.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new LengthFieldPrepender(4));
                    ch.pipeline().addLast(new StringEncoder(StandardCharsets.UTF_8));
                }
            });
            ChannelFuture connect = bootstrap.connect();
            connect.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (future.isSuccess()) {
                        System.out.println("JsonClient 客户端连接成功");
                    } else {
                        System.out.println("JsonClient 客户端连接失败");

                    }
                }
            });
            connect.sync();
            Channel channel = connect.channel();
            for (int i = 0; i < 1000; i++) {
                JsonServer.JsonMsg user = new JsonServer.JsonMsg();
                user.setId(i);
                user.setContent("这是一条测试的数据");
                String msg = JsonUtil.pojoToJson(user);
                channel.writeAndFlush(msg);
                System.out.println("发送数据" + msg);
            }
            channel.flush();
            ChannelFuture closeFuture = channel.closeFuture();
            closeFuture.sync();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            workerGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) {
        new JsonSendClient().runClient();
    }
}
